﻿using System;
using System.Collections.Generic;
using System.Text;
using FangPage.Common;
using FangPage.Core;
using FangPage.Data;
using FangPage.User;
using FangPage.User.Model;

namespace FangPage.User.Controller
{
    public class user_add : UserController
    {
        protected UserInfo userinfo = new UserInfo();

        protected List<RoleInfo> rolelist = new List<RoleInfo>();

        protected List<Department> departlist = new List<Department>();

        public override void Controller()
        {
            string id = FPRequest.GetString("id");

            if (!id.IsNullOrEmpty())
            {
                userinfo = DbHelper.ExcuteModel<UserInfo>(id);
            }

            if (ispost)
            {
                //先确定登录名是否存在
                string username = FPRequest.GetString("username");

                if (username == "")
                {
                    FPResponse.WriteErr("登录名不能为空。");
                    return;
                }

                SqlParam[] check_username =
                {
                    DbHelper.MakeAndWhere("username",username),
                    DbHelper.MakeAndWhere("id",WhereType.NotEqual,id)
                };

                int count = DbHelper.ExcuteCount<UserInfo>(check_username);

                if (count > 0)
                {
                    FPResponse.WriteErr("该登录名已经被使用，请使用别的登录名。");
                    return;
                }

                string password = FPRequest.GetString("password2");

                if (password == "" && id.IsNullOrEmpty())
                {
                    FPResponse.WriteErr("登录密码不能为空。");
                    return;
                }

                string roleid = FPRequest.GetString("roleid");

                if (roleid.IsNullOrEmpty())
                {
                    FPResponse.WriteErr("请选择用户角色。");
                    return;
                }

                userinfo = FPRequest.GetModel(userinfo);

                if (password != "")
                {
                    userinfo.password = FPUtils.MD5(password);
                }

                if (userinfo.id.IsNullOrEmpty())
                {
                    DbHelper.ExcuteInsert(userinfo);

                    FPResponse.WriteSuccess("添加成功");
                }
                else
                {
                    DbHelper.ExcuteUpdate(userinfo);

                    FPResponse.WriteSuccess("修改成功");
                }
            }

            rolelist = DbHelper.ExcuteList<RoleInfo>(OrderBy.ASC);

            SqlParam depart_order = DbHelper.MakeOrderBy("display", OrderBy.ASC);

            departlist = DbHelper.ExcuteList<Department>(depart_order);

            vdata["userinfo"] = userinfo;
            vdata["rolelist"] = rolelist;
            vdata["departlist"] = departlist;

            FPResponse.WriteJson(vdata);
        }
    }
}
